@echo off
setlocal

rem -- Timestamp, might be useful for naming output.  Format is YYMMDD_HHMMSS.
rem -- TODO: Has problem because TIME does not have leading zeros.  Results in a space.

set FDATETIME=%DATE:~12,2%%DATE:~4,2%%DATE:~7,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
if {%date:~8,1%}=={-}  set FDATETIME=%DATE:~6,2%%DATE:~9,2%%DATE:~12,2%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%

rem -- Create the destination directory.  (Useful if it is based on timestamp.)
if not exist "%DSTDIR%"  md "%DSTDIR%"


rem -- Loop through all the files in the source directory.
rem -- We build up the list and when we have enough, we launch ascmd with the list.

set ICLIENT=1
set IFILE=0
set INPUTFILELIST=
for %%G in (%QueryDirectory%\%FILENAMESEARCH%) do call :AddSingleFile %%G

rem -- Check if we did not have enough files for the clients.
rem -- Better to check first but that is more code to write.

if %ICLIENT% LEQ %NUMCLIENTS% (
    @echo.
    @echo ERROR: Not enough files exist for each client.
    @echo.
)

goto :eof


:----------
:AddSingleFile

rem -- For files at the end that aren't used, we just ignore them.
rem -- Ideally we would break out of the calling loop.

if %ICLIENT% GTR %NUMCLIENTS% goto :eof

rem -- Append the file to the list of files for the client we are getting ready to launch.

set INPUTFILELIST=%INPUTFILELIST% -i "%1"
set /a IFILE = %IFILE% + 1
if %IFILE% LSS %NumInputFilesPerClient% goto :eof

rem -- Build up a set of other command line options.

set OTHER=
rem set OTHER=%OTHER% -o "%DSTDIR%\%BASECLIENTOUTFILENAME%_%ICLIENT%.xml"
set OTHER=%OTHER% -oResultStat "%DSTDIR%\%RunInfo%_%FDATETIME%_%ICLIENT%.csv"
rem set OTHER=%OTHER% -RandomSeed %ICLIENT%
set OTHER=%OTHER% -ConnectWaitMin %ConnectWaitMin%
set OTHER=%OTHER% -ConnectWaitMax %ConnectWaitMax%
set OTHER=%OTHER% -ThinkTimeMin %ThinkTimeMin%
set OTHER=%OTHER% -ThinkTimeMax %ThinkTimeMax%
set OTHER=%OTHER% -NoResultStatHeader
set OTHER=%OTHER% -RunInfo "%RunInfo%"

rem -- Launch ascmd to simulate this client.
rem @echo start "RunASCMD %ICLIENT%" /MIN ascmd -S "%SSASServer%" -d "%DATABASE%" %INPUTFILELIST% %OTHER% -Xf quit.txt

@echo on
start "RunASCMD %ICLIENT%" /MIN ascmd.exe -S "%SSASServer%" -d "%DATABASE%" %INPUTFILELIST% %OTHER% -Xf quit.txt
@echo off

rem -- Reset the variables for the current client.

set /a ICLIENT = %ICLIENT% + 1
set IFILE=0
set INPUTFILELIST=
goto :eof


